package cn.edu.zut.qixiang.mock;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 空气数据采集表数据生成器
 * 为空气数据采集站生成模拟数据（每隔10分钟采集一次）
 * @author 86178
 */
public class AirDataGenerator {

    // 数据库配置
    private static final String URL = "jdbc:mysql://localhost:3306/qixiang_base?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8";
    private static final String USER = "root";
    private static final String PASSWORD = "520521fcf..@1234";

    // 数据生成参数
    private static final int BATCH_SIZE = 100;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        generateAirData();
    }

    /**
     * 生成空气数据（每隔10分钟采集一次）
     */
    public static void generateAirData() {
        String selectStationsSql = "SELECT station_id FROM collection_stations WHERE station_type = '空气数据采集站' ORDER BY station_id";
        String insertDataSql = "INSERT INTO air_data (" +
                "collection_station_id, cloud_cover, visibility, pm25, pm10, " +
                "so2, no2, co, o3, collection_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement selectStmt = conn.prepareStatement(selectStationsSql);
             PreparedStatement insertStmt = conn.prepareStatement(insertDataSql)) {

            conn.setAutoCommit(false);
            Random random = new Random();

            // 获取所有空气数据采集站
            ResultSet stationRs = selectStmt.executeQuery();

            int batchCount = 0;
            int totalRecords = 0;
            int stationCount = 0;

            // 生成2025年5月1日到9月1日的数据，每10分钟一次
            LocalDateTime startTime = LocalDateTime.of(2025, 5, 1, 0, 0, 0);
            LocalDateTime endTime = LocalDateTime.of(2025, 9, 1, 23, 50, 0);

            System.out.println("开始生成空气数据...");
            System.out.println("时间范围: " + startTime.format(DATE_FORMATTER) + " 到 " + endTime.format(DATE_FORMATTER));
            System.out.println("采集频率: 每10分钟一次");

            // 遍历每个空气采集站
            while (stationRs.next()) {
                int stationId = stationRs.getInt("station_id");
                stationCount++;
                System.out.println("为采集站 " + stationId + " 生成数据...");

                LocalDateTime currentTime = startTime;

                // 为每个时间点生成数据（每10分钟一次）
                while (!currentTime.isAfter(endTime)) {
                    // 生成模拟数据
                    int hour = currentTime.getHour();
                    boolean isDaytime = hour >= 6 && hour <= 18;

                    // 云量 (0-100%)
                    int cloudCover = isDaytime ? random.nextInt(70) + 10 : random.nextInt(50) + 20;

                    // 能见度 (km)
                    double visibilityBase = isDaytime ? 15.0 : 12.0;
                    double visibility = Math.round((visibilityBase + random.nextDouble() * 10 - 3) * 10) / 10.0;

                    // PM2.5浓度 (μg/m³)
                    double pm25Base = isDaytime ? 35.0 : 45.0;
                    double pm25 = Math.round((pm25Base + random.nextDouble() * 40 - 15) * 10) / 10.0;

                    // PM10浓度 (μg/m³)
                    double pm10Base = pm25Base * 1.8;
                    double pm10 = Math.round((pm10Base + random.nextDouble() * 60 - 20) * 10) / 10.0;

                    // SO2浓度 (μg/m³)
                    double so2 = Math.round((5 + random.nextDouble() * 15) * 10) / 10.0;

                    // NO2浓度 (μg/m³) - 交通高峰期更高
                    double no2Base = (hour >= 7 && hour <= 9) || (hour >= 17 && hour <= 19) ? 50.0 : 30.0;
                    double no2 = Math.round((no2Base + random.nextDouble() * 20 - 10) * 10) / 10.0;

                    // CO浓度 (mg/m³)
                    double co = Math.round((0.5 + random.nextDouble() * 1.0) * 10) / 10.0;

                    // O3浓度 (μg/m³) - 白天光照强时臭氧浓度更高
                    double o3Base = isDaytime ? 80.0 : 40.0;
                    double o3 = Math.round((o3Base + random.nextDouble() * 40 - 20) * 10) / 10.0;

                    // 设置插入参数
                    insertStmt.setInt(1, stationId);
                    insertStmt.setInt(2, cloudCover);
                    insertStmt.setDouble(3, visibility);
                    insertStmt.setDouble(4, pm25);
                    insertStmt.setDouble(5, pm10);
                    insertStmt.setDouble(6, so2);
                    insertStmt.setDouble(7, no2);
                    insertStmt.setDouble(8, co);
                    insertStmt.setDouble(9, o3);
                    insertStmt.setString(10, currentTime.format(DATE_FORMATTER));

                    insertStmt.addBatch();
                    batchCount++;
                    totalRecords++;

                    // 批量提交
                    if (batchCount % BATCH_SIZE == 0) {
                        insertStmt.executeBatch();
                        conn.commit();
                        System.out.println("已提交 " + batchCount + " 条记录，总计 " + totalRecords + " 条");
                    }

                    // 时间增加10分钟
                    currentTime = currentTime.plusMinutes(10);
                }
            }

            // 提交剩余数据
            if (batchCount % BATCH_SIZE != 0) {
                insertStmt.executeBatch();
                conn.commit();
            }

            System.out.println("空气数据生成完成！");
            System.out.println("共为 " + stationCount + " 个采集站生成 " + totalRecords + " 条记录");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}